import re

def extract_values_from_log_file(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
        pattern = r"mAP:\s+(\d+\.\d+)|accuracy:\s+(\d+\.\d+)"
        matches = re.findall(pattern, content)
        values = [float(match[0] or match[1]) for match in matches]
        return values

def extract_cka_values_from_log_file(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
        # pattern = r"ece:\s+(\d+\.\d+)"
        pattern = r"avg_acc:\s+(\d+\.\d+)"
        matches = re.findall(pattern, content)
        values = matches
        return values

def write_to_txt(file_path, data, num_per_row, empty_row_interval):
    with open(file_path, 'w') as file:
        for i in range(0, len(data), num_per_row):
            row = data[i:i+num_per_row]
            line = '\t'.join(str(round(float(value), 4)) for value in row)
            file.write(line)
            file.write('\n')
            
            # Insert an empty line after every `empty_row_interval` rows
            if (i + num_per_row) % (num_per_row * empty_row_interval) == 0:
                file.write('\n')

log_file_path = "Main_results/figure4/4_acc_ece/logs/7_colon.log"
cka_txt_file_path = "avg_acc_tmp.txt"

ece_values = extract_cka_values_from_log_file(log_file_path)
if ece_values:
    write_to_txt(cka_txt_file_path, ece_values, 5, 9)
    print("Output saved to TXT file.")
else:
    print("Values not found in the log file.")